from flask import session, current_app, jsonify, g, request
from modules import db
from modules.commons import user_login_data
from modules.constants import QINIU_URL_DOMAIN
from modules.home import my_blue
from modules.models import User
from modules.utils.image_storage import image_storage
from modules.utils.response_code import RET


@my_blue.route('/user/name', methods=['POST'])
@user_login_data
def update_name():
    """
    功能：修改用户昵称
    请求路径：/api/v1.0/user/name
    请求方式：POST
    请求参数：name
    :return:响应状态
    """
    user_name = request.json.get('name')
    if not user_name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数为空')
    try:
        g.user.name = user_name
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='姓名保存失败')
    return jsonify(errno=RET.OK, errmsg='OK')


@my_blue.route('/user/avatar', methods=['POST'])
@user_login_data
def update_avatar():
    """
    功能：修改用户头像
    请求路径：/api/v1.0/user/avatar
    请求方式：POST
    请求参数：avatar
    :return:图片路径及响应
    """
    image_data = request.files.get('avatar')
    if not image_data:
        return jsonify(errno=RET.NODATA, errmsg='图片上传失败')
    avatar_url = image_storage(image_data.read())
    avatar_url = QINIU_URL_DOMAIN + avatar_url
    try:
        g.user.avatar_url = avatar_url
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='图片保存失败')
    data = {
        'avatar_url':avatar_url
    }
    return jsonify(errno=RET.OK, errmsg='图片上传成功', data=data)
